<template>
    <div>
      <DxPopup class="PortletDxPopup" :show-title="true" :title="title" :visible="dialogVisible"
        :close-on-outside-click="false" :show-close-button="false" width="800" :height="600" :shading="false"
        :resizeEnabled="true">
        <DxScrollView width="100%" height="100%">
          <div class="dialogContent" style="padding:10px 20px">
            <el-row>
              <el-col style="min-height: 500px;">
                <div class="config-title"></div>
                <div class="grid-content bg-purple">
                    <el-form label-width="100px" @submit.native.prevent v-if="element && element.options && element.options.inParams.length>0">
                      <div style="width: 100%;">
                          <label class="el-form-item__label" style="text-align: left;font-weight: 600;">{{ Terms.mutual.paramBind}}</label>
                          <el-tooltip  class="item" effect="dark" :content="Terms.mutual.paramBindeExplain" placement="right">
                            <i class="el-icon-question" style="cursor: pointer;pointer-events: auto;line-height: 40px;}"></i>
                          </el-tooltip>
                      </div>

                      <template v-for="param in element.options.inParams">
                        <div class="field">
                            <label class="el-form-item__label" style="width: 100%;text-align: left;">{{param.Name}}</label>
                            <el-select @change="onParamChanged($event,param)" v-model="param.Value" :placeholder="Terms.mutual.paramBindPlaceholder" size="small">
                                <el-option v-for="item in localVarsObjectList" :label="item.name" :value="item.value" :key="item.value"></el-option>            
                            </el-select>
                        </div>
                      </template>
                    </el-form>
                    <el-form label-width="100px" @submit.native.prevent style="margin-top:10px;">
                      <div style="width: 100%;">
                          <label class="el-form-item__label" style="text-align: left;font-weight: 600;">{{ Terms.mutual.eventBind}}</label>
                          <el-tooltip  class="item" effect="dark" :content="Terms.mutual.eventBindExplain" placement="right">
                            <i class="el-icon-question" style="cursor: pointer;pointer-events: auto;line-height: 40px;}"></i>
                          </el-tooltip>
                      </div>
                      <template v-for="(eventItem,index) in relationEventList">
                        <div class="field">
                            <label class="el-form-item__label" style="width: 100%;text-align: left;">{{ Terms.mutual.relationObject}}</label>
                            <el-select @change="relationObjectChange($event,index)" v-model="eventItem.relationObject" :placeholder="Terms.mutual.relationObject" size="small">
                                <el-option v-for="item in relationObjectList" :label="item.name" :value="item.value" :key="item.value"></el-option>            
                            </el-select>
                        </div>
                        <div class="field">
                            <label class="el-form-item__label" style="width: 100%;text-align: left;">{{ Terms.mutual.relationObjectEvent}}</label>
                            <el-select v-model="eventItem.relationObjectEvent" :placeholder="Terms.mutual.relationObjectEvent" size="small">
                                <el-option v-for="item in eventItem.relationObjectEventList" :label="item.Name" :value="item.Code" :key="item.ID"></el-option>
                            </el-select>
                        </div>
                        <div class="field">
                            <label class="el-form-item__label" style="width: 100%;text-align: left;">{{ Terms.mutual.responseEvent}}</label>
                            <el-select v-model="eventItem.responseEvent" :placeholder="Terms.mutual.responseEvent" size="small">
                                <el-option v-for="item in responseEventList" :label="item.Name" :value="item.Code" :key="item.Code"></el-option>
                            </el-select>
                        </div>
                        <div style="display:inline-block;">
                          <el-button type="primary" @click="addRow(index,$event)" icon="el-icon-plus" size="mini" circle></el-button>
                          <el-button icon="el-icon-close" @click="removeRow(index,$event)" size="mini" circle></el-button>
                        </div>
                      </template>

                    </el-form>
                </div>
              </el-col>
  
            </el-row>
          </div>
        </DxScrollView>

        <DxToolbarItem toolbar="bottom" location="after">
          <el-button type="primary" style="position: relative;float: right;margin-top: 10px;margin-right: 10px;z-index: 3000 !important;" @click="sureData" size="small">{{Terms.portal.confirm}}</el-button>
      </DxToolbarItem>
      <DxToolbarItem toolbar="bottom" location="after">
        <el-button  style="position: relative;float: right;margin-top: 10px;margin-right: 10px;z-index: 3000 !important;" @click="closeHelper" size="small">{{Terms.portal.cancel}}</el-button>
      </DxToolbarItem>
        <DxToolbarItem widget="dxButton" toolbar="top" location="after" :options="topcloseButtonOptions" />
      </DxPopup>
    </div>
  </template>
  
  <script>
  import { DxPopup, DxToolbarItem } from "devextreme-vue/popup";
  import { DxScrollView } from "devextreme-vue/scroll-view";
  import DxButton from "devextreme-vue/button";
  import {createWidgetEvent,createSubscribeInfo} from './mutualUtils'
  import { Terms } from "./lib/Term";
  const specFlag = '-x-x-x-'

  export default {
    data() {
      return {
        localVarsObjectList:[],
        Terms:Terms,
        dialogVisible: false,
        title: Terms.mutual.title,
        loading: false,
        relationEventList:[{
          relationObject:null,
          relationObjectEvent:null,
          responseEvent:null,
          relationObjectEventList:[],
        }],
        relationObjectList:[],
        responseEventList:[],
        buttonAttributes: {
          class: "customColor",
        },
        sureButtonOptions: {
          icon: "check",
          text: "确定",
          type: "default",
          elementAttr: this.buttonAttributes,
          onClick: () => {
            //            this.dialogVisible = false;
            this.sureData();
          },
        },
        closeButtonOptions: {
          icon: "close",
          text: "取消",
          onClick: () => {
            this.dialogVisible = false;
          },
        },
        topcloseButtonOptions: {
          icon: "close",
          stylingMode: "text",
          onClick: () => {
            this.dialogVisible = false;
          },
        },
      };
    },
    props: [
      "args","allComponentInfo"
    ],
    components: {
      DxPopup,
      DxScrollView,
      DxToolbarItem,
      DxButton,
    },
    mounted(){

    },
    methods: {
      closeHelper(){
        this.dialogVisible = false
        this.element.options.inParams = this.bkInParams
      },
      onParamChanged(evt,item){

        item.Value = evt
        if(!evt){
          item.DefaultValue = specFlag
        }

        Widget[this.element.InstanceCode].registPortletVarWatch(item.Code,item.Value)
        //this.$parent.layoutChanged = true
      },
      relationObjectChange(val,index){
            
        if(Widget[val].widget.ucPageMetadata){
            this.relationEventList[index].relationObjectEventList = Widget[val].widget.ucPageMetadata.CtrlEvents
        }else {
            let result = []
            let tag = Widget[val].widget.Tag
            this.allComponentInfo.filter(item=>item.MetaDataCode == tag)[0].Events.forEach(element => {
                result.push({
                    Code:element.Name,
                    Name:element.Description
                })
            });
            // Widget[val].widget.Events.forEach(element => {
            //     result.push({
            //         Code:element.Name,
            //         Name:element.Name
            //     })
            // });
            this.relationEventList[index].relationObjectEventList = result
        }
        this.relationEventList[index].relationObjectEvent = null
        this.relationEventList[index].responseEvent = null
      },
      addRow(index){
        this.relationEventList.splice(index+1,0,{
          relationObject:null,
          relationObjectEvent:null,
          relationObjectList:[],
          responseEvent:null,
        })
      },
      removeRow(index){
        if(index==0){
          this.relationEventList = [{
            relationObject:null,
            relationObjectEvent:null,
            responseEvent:null,
            relationObjectEventList:[],
          }]
          return 
        }
        this.relationEventList.splice(index,1)
      },
      handleSelect(item) {
        this.$emit("sureData", {
          data: item
        });
  
        this.dialogVisible = false;
      },
      open: function (row) {
debugger
        this.element = row
        this.title = Terms.mutual.title +'-'+ this.element.options.title

        this.bkInParams = JSON.parse(JSON.stringify(this.element.options.inParams))    

        this.element.options.inParams.forEach(item=>{
          if(item.DefaultValue == specFlag)item.DefaultValue=''
          if(item.Value == specFlag)item.Value=''
          if(typeof item.Value === 'object'){
            item.Value=''
          }
        })

        this.dialogVisible = true;
        // this.relationObject = null
        // this.relationObjectEvent = null
        // this.responseEvent = null
        this.relationEventList = []

        
        this.localVarsObjectList = [{value:'',name:''}]
        for(let key in LocalVars){
          if(key.startsWith('fas_portlet') || key.startsWith('_') || key == 'id')continue
          let lvItem = pageMetaData.LocalVariables.filter(item=>item.Code==key)
          this.localVarsObjectList.push({
            name:(lvItem && lvItem.length>0)? lvItem[0].Name : key,
            value:`LocalVars.${key}`
          })
        }

        let initObj = {
          relationObject:null,
          relationObjectEvent:null,
          relationObjectList:[],
          responseEvent:null,
        }
        debugger
        let _coms = _.pickBy(Widget,(value,key)=>{return key.startsWith('fas_')})
        let result = []
        for(let key in _coms){
            let valObj = _coms[key]
            let name = key.startsWith('fas_portlet')?valObj.options.title:(valObj.options.label || valObj.options.text)
            result.push({
                name:name,
                value:key
            })
        }

        this.relationObjectList = result.filter(item=>item.value!=this.element.InstanceCode)

        this.responseEventList = Widget[this.element.InstanceCode].widget.ucPageMetadata.CtrlMethods
        
        this.responseEventList = this.responseEventList.filter(item=>item.Code!= 'RefreshPortlet')
        if(this.responseEventList.filter(item=>item.Code== 'Refresh').length==0){
            this.responseEventList.push({
                Code:'Refresh',
                Name:Terms.contextMenu.refresh
            })
        }

        this.relationEventList.push(initObj)

        //還原
        if(this.element.options.relation && this.element.options.relation.length > 0){
          this.relationEventList = []
          this.element.options.relation.forEach(item=>{
            let info = JSON.parse(item.SubscribeActionContent)
            this.relationEventList = this.relationEventList.concat(info.eventObjectList)
            //  createSubscribeInfo(info.key,info.eventName,info.eventObjectList,this.element)
            // this.relationEventList.push(subscribeInfo)
          })
        }

      },
      getGuid() {
        function t() {
            return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
        }
        return (
            t() + t() + "-" + t() + "-" + t() + "-" + t() + "-" + t() + t() + t()
        );
      },
      sureData: async function () {

        let hasError = false
        this.relationEventList.forEach(item=>{
          if(!item.relationObject && !item.relationObjectEvent && !item.responseEvent){return true}
          if (!item.relationObject || !item.relationObjectEvent || !item.responseEvent) {          
              hasError = true
              return false;
          }
         })

         if(hasError){
          return Funcs.Notify(Terms.message.warn, Terms.message.mutualWarnMessage, 'warning')
         }
   
         //清理全空行
         let newList = this.relationEventList.filter(item=>item.relationObject && item.relationObjectEvent && item.responseEvent)
         this.relationEventList = newList
         debugger
         if(JSON.stringify(this.element.options.relation) != JSON.stringify(newList)){
          this.$parent.layoutChanged = true
         }
         if(JSON.stringify(this.element.options.inParams) != JSON.stringify(this.bkInParams)){
          this.$parent.layoutChanged = true
         }
 

         this.element.options.relation =  []
         //关系插入widget同时入库
         createWidgetEvent(this)         

         
debugger
          //确定后再插入
        //   let action = {
        //     "ID": this.getGuid(),
        //     "Code": "",
        //     "Name": "OnChange",
        //     "ComponentID": null,
        //     "InstanceCode": this.relationObject,
        //     "ActionType": -1,
        //     "ActionID": "",
        //     "DisplayInfo": "",
        //     "ActionSourceType": 0,
        //     "ActionSourceID": "",
        //     "JSScript": "",
        //     "JSScriptES5": ""
        // }
 
          // return
          this.$emit("sureData", {
              data: this.selectedRow
          });
  
          this.dialogVisible = false;
      },
      handleCurrentChange: function (val) {
        console.log(val)
        this.selectedRow = val;
        this.renderPreview()
      },
      getMetaData: function () {
        this.loading = true;
        var that = this;
        // if (!window.FrameSGHost) window.FrameSGHost = "http://sgi.teld8.xyz:7777/api/invoke?SID="
        // let sgUrl = (window.FrameSGHost + 'FASD-ProjectQueryMetaDataHelp')
        // this.$route.query.branchID = 'd9f95a66-eac1-4451-8075-8c9d441c56'
        // this.$route.query.id = '2a18bab6-08f6-4030-a91e-97c4b0b0337'
        // let postData = {
        //   projectBranchId: this.$route.query.branchID,
        //   metatypeid: 'UIControl',
        //   projectid: this.$route.query.id,
        //   condition: this.condition
        // }
        // //TeldFasRTUtils.fasApi.Funcs.Base.GetDataAsync
        // window.getDataAsync(sgUrl, "post", { filter: JSON.stringify(postData) }, function (result) {
  
        //   that.loading = false;
        //   if (result) {
        //     console.log(result);
        //     let tableData = result;
        //     that.tableData = tableData.slice(0);
  
        //   }
        // })
        let sgUrl = window.FrameSGHost + 'FASR-GetPortletMetadatas'
        let postData = {
          SubSystemCode: window.getFasDevAppId(),
          ModuleCode: '',
          FilterKey: this.condition
        }
  
        window.getDataAsync(sgUrl, "post", { filter: JSON.stringify(postData) }, function (result) {
  
          that.loading = false;
          if (result) {
            console.log(result);
            let tableData = result.data;
            that.tableData = tableData.slice(0);
  
          }
        })
  
        this.loading = false;
      },
      search: function () {
        this.getMetaData();
      },
      clearSearch: function () {
        this.condition = "";
        this.getMetaData();
      },
      renderPreview(){
        if(!this.selectedRow)return
        let id = this.selectedRow.MetaDataID;
        let root = location.href.split('?')[0]
        let url = `${root}?id=${id}`
        this.$refs.portletPreviewFrame.src = url
      }
    },
    // watch:{
    //     relationObject:function(val){



    //     }
    // }
  };
  </script>
  
  <style lang="scss" scoped>
.field{
  width: 30%;
  display:inline-block;
}
.current-selected {
    padding: 16px 10px;
    width: 200px;
    height: 120px;
    margin-right: 10px;
    box-shadow: 0 0 10px #525252;
    background-size: 240px 180px;
  
    .label {
      font-size: 1.5em;
      font-weight: bold;
      line-height: 1.8em;
      color: #f8f8fa;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      margin-bottom: .4em;
    }
  
    .tips {
      font-size: 1.1em;
      color: #c9c9cf;
      height: 1.4em;
      line-height: 1.4em;
      padding-bottom: 0.4em;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
  
  .material-wrapper {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    font-size: 16px;
  
    .material-fake {
      width: 10em;
      height: 0;
      margin: 0 .2em;
    }
  
    .material {
      width: 10em;
      height: 12em;
      box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
      // border-radius: 8px;
      margin: .8em .2em;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      cursor: pointer;
      transition: transform .4s ease-in-out;
  
      &:hover {
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3), 0 10px 10px -5px rgba(0, 0, 0, 0.1);
  
        .img-wrapper {
          img {
            transform: scale(1.05);
          }
        }
      }
  
      .img-wrapper {
        background: linear-gradient(45deg, rgb(211, 208, 253), rgb(208, 227, 253));
        position: relative;
        width: 10em;
        height: 8em;
        overflow: hidden;
  
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform .4s ease-in-out;
        }
      }
  
      .content {
        padding: .4em .4em .8em;
  
        .label {
          font-size: 1.1em;
          font-weight: bold;
          line-height: 1.8em;
          color: #262626;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
  
        .tips {
          font-size: 0.8em;
          color: #686872;
          height: 1.2em;
          line-height: 1.2em;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
      }
    }
  }
  
  @media screen and (max-width: 480px) {
    .material-wrapper {
      font-size: 14px;
    }
  }
  </style>
  